package huhx.linux.com.kotlinlearn.widget

import android.content.Context
import android.view.Gravity
import android.widget.Toast

/**
 * Created by huhx on 2018-03-17 下午 11:19.
 */

class SimpleToast private constructor(context: Context) {
    private var mToast: Toast? = null
    private var nextTimeMillis: Long = 0
    private var yOffset: Int = 0

    fun show(content: String, duration: Int = Toast.LENGTH_SHORT) {
        show(null, content, Gravity.BOTTOM, duration)
    }

    fun show(context: Context, rid: Int) {
        show(context, context.resources.getString(rid))
    }

    fun init(context: Context): Toast {
        if (context == null) {
            throw IllegalArgumentException("Context should not be null!!!")
        }
        if (mToast == null) {
            mToast = Toast.makeText(context, null, Toast.LENGTH_SHORT)
            yOffset = mToast!!.yOffset
        }
        mToast!!.duration = Toast.LENGTH_SHORT
        mToast!!.setGravity(Gravity.BOTTOM, 0, yOffset)
        mToast!!.setMargin(0f, 0f)
        return mToast!!
    }

    fun show(context: Context?, content: String, gravity: Int = Gravity.BOTTOM, duration: Int = Toast.LENGTH_SHORT) {
        val current = System.currentTimeMillis()
        //if (current < nextTimeMillis) return;
        if (mToast == null) init(context!!.applicationContext)
        mToast!!.setText(content)
        mToast!!.duration = duration
        mToast!!.setGravity(gravity, 0, yOffset)
        nextTimeMillis = current + if (duration == Toast.LENGTH_LONG) 3500 else 2000
        mToast!!.show()
    }
}
